package tech.yozo.bamboo.ui.reading;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;

import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import java.io.IOException;

import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import tech.yozo.bamboo.databinding.FragmentReadBookBinding;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ReadBookFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ReadBookFragment extends Fragment {
    private ReadingViewModel model;
    private FragmentReadBookBinding binding;

    private static final String baseUrl = "https://example.com/";

    private int page = 1;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public ReadBookFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ReadEpubFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ReadBookFragment newInstance(String param1, String param2) {
        ReadBookFragment fragment = new ReadBookFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 绑定数据
        model = new ViewModelProvider(requireActivity()).get(ReadingViewModel.class);
        LiveData<Book> bookLiveData = model.getBook();
        bookLiveData.observe(getViewLifecycleOwner(), this::openBook);

        // 绑定视图
        binding = FragmentReadBookBinding.inflate(inflater, container, false);
        binding.bookView.setOnTouchListener((v, event) -> gestureDetector.onTouchEvent(event));
        binding.bookView.setOnSelectedTextListener(model::doSelectText);
        binding.bookView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 100) {
                    binding.progressBar.setVisibility(View.GONE);
                } else {
                    binding.progressBar.setVisibility(View.VISIBLE);
                    binding.progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("iReading", consoleMessage.message() + " -- From line " +
                        consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());
                return true;
            }
        });

        return binding.getRoot();
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void onResume() {
        binding.bookView.getSettings().setJavaScriptEnabled(true);
        super.onResume();
    }

    @Override
    public void onPause() {
        binding.bookView.getSettings().setJavaScriptEnabled(false);
        super.onPause();
    }

    private final GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onFling(@Nullable MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY) {
            // 翻页
            if (e1 != null &&
                    Math.abs(e1.getX() - e2.getX()) > 100 &&
                    Math.abs(velocityX) - Math.abs(velocityY) > 200) {
                Book book = model.getBook().getValue();
                if (velocityX > 0) {
                    // 向左滑动
                    page -= 1;
                    openBook(book);
                } else {
                    // 向右滑动
                    page += 1;
                    openBook(book);
                }
                return true;
            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    });

    private void openBook(Book book) {
        if (book == null) {
            return;
        }
        long time = System.currentTimeMillis();
        if (page >= book.getSpine().size() || page < 0) {
            page = 0;
        }
        Resource resource = book.getSpine().getResource(page);
        String mimeType = null;
        if (resource.getMediaType() != null) {
            mimeType = resource.getMediaType().toString();
        }
        String encoding = resource.getInputEncoding();

        String data;
        try {
            data = new String(resource.getData());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        binding.bookView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, null);
        Log.i("iReading", "epub open time: " + (System.currentTimeMillis() - time));
    }
}